#ifndef __SingletonHolder_H__
#define __SingletonHolder_H__

#include <stdlib.h>

template<typename T>
class SingletonHolder
{
public:
	static T& Instance();

private:
	//Helpers
	static void Create();
	static void OnDeadReference();
	static void KillPhoenixSingleton();

	//Data
	static T* pInstance_;
	static bool destroyed_;

	//Protection
	SingletonHolder();
	virtual ~SingletonHolder();
	SingletonHolder(const SingletonHolder&);
	SingletonHolder& operator=(const SingletonHolder&);
};

template<typename T>
T& SingletonHolder<T>::Instance()
{
	if (!pInstance_) {
		if (destroyed_)
			OnDeadReference();
		else
			Create();
	}
	return *pInstance_;
}

template <typename T>
void SingletonHolder<T>::Create()
{
	static T theInstance;
	pInstance_ = &theInstance;
}

template <typename T>
void SingletonHolder<T>::OnDeadReference()
{
	Create();
	new(pInstance_) T;
	atexit(KillPhoenixSingleton);
	destroyed_ = false;
}

template <typename T>
void SingletonHolder<T>::KillPhoenixSingleton()
{
	pInstance_ = 0;
	destroyed_ = true;
	pInstance_->~T();
}

template <typename T> T* SingletonHolder<T>::pInstance_ = 0;
template <typename T> bool SingletonHolder<T>::destroyed_ = false;

template <typename T>
SingletonHolder<T>::SingletonHolder() {}

template <typename T>
SingletonHolder<T>::~SingletonHolder() {}

template <typename T>
SingletonHolder<T>::SingletonHolder(const SingletonHolder<T>&) {}

template <typename T>
SingletonHolder<T>& SingletonHolder<T>::operator=(const SingletonHolder&)
{
	return *this;
}

#endif
